//$Id: RegisterAction.java 5298 2007-06-20 00:08:47Z gavin $
package org.jboss.seam.example.registration;

import java.util.List;

import javax.persistence.EntityManager;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

//@Stateless
@Name("register") 
public class RegisterAction //implements Register 
{

	@In
	private User user;

//	@PersistenceContext
//	@Out(value = "entityManager", scope = ScopeType.SESSION)
	@In("userDatabase")
	private EntityManager em;

	@Logger
	private static Log log;

	@SuppressWarnings("unchecked")
	public String register() {
		List<String> existing = em
				.createQuery(
						"select u.username from User u where u.username=#{user.username}")
				.getResultList();

		if (existing.size() == 0) {
			em.persist(user);
			log.info("Registered new user #{user.username}");
			return "/registered";
		} else {
			FacesMessages.instance()
					.add("用户 #{user.username} 已存在");
			log.info("试图注册的用户名已存在！！");
			return null;
		}
	}

}
